﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using NxERP.Bll;

using NxStoreManage;

namespace LengthAiCalculate
{
    public partial class ResultForm : BaseForm
    {
        private readonly AiResult result = null;
        private readonly string sheetName = "Sheet1";
        private Dictionary<double, ResultTable> resultTable;
        private DataTable jhDt;
        private int SleepTime = 300;

        public ResultForm(AiResult _aiResult, string txt, string _sheetName, Dictionary<double, ResultTable> resultTable, DataTable jhDt)
        {
            InitializeComponent();
            result = _aiResult;
            Text = txt;
            if (_sheetName != null)
            {
                sheetName = _sheetName;
                sheetName = sheetName.Replace('*', 'x');
                label3.Text = _sheetName.Split('_')[0];
                label4.Text = _sheetName.Split('_')[1];
                label9.Text = _aiResult.AchievePercent.ToString() + "%";
                label11.Text = _aiResult.NoAchievePercent.ToString() + "%";
                label12.Text = _aiResult.DifficultyValue.ToString();
            }
            else
            {
                label3.Text = "未输入";
                label4.Text = "未输入";
                label9.Text = "0%";
                label11.Text = "0%";
                label12.Text = "0";
            }
            this.resultTable = resultTable;
            this.jhDt = jhDt;
        }

        private void ResultForm_Load(object sender, System.EventArgs e)
        {
            label30.Text = "说明：从锯切组合表中选择已完成计算的组合，或者手工输入组合，手工输入格式：长度*支数+长度*支数......，如果支数为1可以省略，比如8+6*5，代表8米1支+6米*5支；输入正确锯切组合后，填写大料支数，点模拟生产即可；提示成功后，在订单匹配结果表中最后一列已生产会更新数据，红色的即为更新的数据。";
            if (result.CutGroupTable != null)
            {
                dataGridView3.DataSource = result.CutGroupTable;
                dataGridView3.Columns[0].HeaderText = "是否有非计划";
                dataGridView3.Columns[1].HeaderText = "大料长度";
                dataGridView3.Columns[2].HeaderText = "大料支数";
                dataGridView3.Columns[3].HeaderText = "锯切组合";
                dataGridView3.Columns[3].Width = 200;
                groupBox4.Text = "锯切组合表，共计：" + result.CutGroupTable.Rows.Count.ToString() + "种组合";
            }
            if (result.MaterialUseTable != null)
            {
                dataGridView4.DataSource = result.MaterialUseTable;
                dataGridView3.Columns[3].Width = 200;
                dataGridView4.Columns[0].HeaderText = "大料长度";
                dataGridView4.Columns[1].HeaderText = "大料支数";
                dataGridView4.Columns[2].HeaderText = "使用支数";
                dataGridView4.Columns[3].HeaderText = "剩余支数";
            }
            SetDataGridDefault(dataGridView1);
            SetDataGridDefault(dataGridView4);
            SetDataGridDefault(dataGridView3);
            dataGridView4.Columns[0].Width = 80;
            dataGridView4.Columns[1].Width = 80;
            dataGridView4.Columns[2].Width = 80;
            dataGridView4.Columns[3].Width = 80;
            Jhsj();
        }

        public void Jhsj()
        {
            Dictionary<double, ResultTable> _resultTable = new Dictionary<double, ResultTable>();
            foreach (DataRow row in jhDt.Rows)
            {
                double oldJhLength = double.Parse(row["lg"].ToString().Trim());
                int oldJhNum = int.Parse(row["num"].ToString().Trim());
                if (!_resultTable.ContainsKey(oldJhLength))
                {
                    _resultTable.Add(oldJhLength, new ResultTable { JhNum = oldJhNum, RealNum = 0 });
                }
            }
            for (int i = 0; i < dataGridView3.Rows.Count; i++)
            {
                string[] arr = dataGridView3.Rows[i].Cells[3].Value.ToString().Split('+');
                int count = int.Parse(dataGridView3.Rows[i].Cells[2].Value.ToString());
                for (int j = 0; j < arr.Length; j++)
                {
                    string[] dat = arr[j].Split('*');
                    double length = double.Parse(dat[0]);
                    int num = int.Parse(dat[1]) * count;
                    int jhNum = 0;
                    DataRow[] jhNumRow = jhDt.Select("lg='" + length + "'");
                    if (jhNumRow.Length > 0)
                    {
                        jhNum = int.Parse(jhNumRow[0]["num"].ToString());
                    }
                    if (_resultTable.ContainsKey(length))
                    {
                        _resultTable[length].RealNum += num;
                        _resultTable[length].JhNum = jhNum;
                    }
                    else
                    {
                        _resultTable.Add(length, new ResultTable { JhNum = jhNum, RealNum = num });
                    }
                }
            }
            if (resultTable.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("长度", typeof(double));
                dt.Columns.Add("需求支数", typeof(int));
                dt.Columns.Add("计算产出支数", typeof(int));
                dt.Columns.Add("计算欠支数", typeof(int));
                dt.Columns.Add("实际欠支数", typeof(int));
                dt.Columns.Add("已生产支数", typeof(int));
                foreach (var item in _resultTable)
                {
                    DataRow dataRow = dt.NewRow();
                    dataRow["长度"] = item.Key;
                    dataRow["需求支数"] = item.Value.JhNum;
                    dataRow["计算产出支数"] = item.Value.RealNum;
                    dataRow["计算欠支数"] = item.Value.JhNum - item.Value.RealNum;
                    dataRow["实际欠支数"] = item.Value.JhNum;
                    dataRow["已生产支数"] = 0;
                    dt.Rows.Add(dataRow);
                }
                dt.DefaultView.Sort = "长度 desc";
                dataGridView1.DataSource = dt;
            }
        }

        private void DataGridView3_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                textBox1.Text = dataGridView3.Rows[e.RowIndex].Cells[3].Value.ToString();
                textBox2.Text = dataGridView3.Rows[e.RowIndex].Cells[2].Value.ToString();
            }
            foreach (DataGridViewRow row3 in dataGridView1.Rows)
            {
                row3.Cells["已生产支数"].Style.BackColor = System.Drawing.Color.White;
            }
        }

        private void Button2_Click(object sender, System.EventArgs e)
        {
            int.TryParse(textBox2.Text, out int bignum);
            if (bignum < 1)
            {
                MessageBox.Show("支数必须大于0！", "提示！", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Error);
                return;
            }
            if (textBox1.Text.Length == 0)
            {
                MessageBox.Show("锯切组合不能为空！", "提示！", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Error);
                return;
            }
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.Cells["已生产支数"].Style.BackColor = System.Drawing.Color.White;
            }
            if (dataGridView3.SelectedRows.Count > 0)
            {
                dataGridView3.SelectedRows[0].DefaultCellStyle.SelectionBackColor = System.Drawing.Color.YellowGreen;
                dataGridView3.SelectedRows[0].DefaultCellStyle.SelectionForeColor = System.Drawing.Color.Black;
            }
            string[] cuttable = textBox1.Text.Trim().Split('+');
            foreach (var item in cuttable)
            {
                string[] o = item.Split('*');
                decimal length = 0;
                int num = 1;
                if (o.Length == 1)
                {
                    decimal.TryParse(o[0], out length);
                }
                else if (o.Length == 2)
                {
                    decimal.TryParse(o[0], out length);
                    int.TryParse(o[1], out num);
                }
                if (length <= 0 || num <= 0)
                {
                    MessageBox.Show("锯切组合表不正确！", "提示！", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Error);
                    return;
                }
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    string _length = row.Cells["长度"].Value.ToString().Trim();
                    if (_length == length.ToString())
                    {
                        int _num = int.Parse(row.Cells["已生产支数"].Value.ToString().Trim());
                        row.Cells["已生产支数"].Value = _num + num * bignum;
                        row.Cells["已生产支数"].Style.BackColor = System.Drawing.Color.YellowGreen;
                    }
                    int jhNum = int.Parse(row.Cells["需求支数"].Value.ToString());
                    int scNum = int.Parse(row.Cells["已生产支数"].Value.ToString());
                    row.Cells["实际欠支数"].Value = jhNum - scNum;
                }
            }
            foreach (DataGridViewRow row in dataGridView3.Rows)
            {
                string cut = row.Cells[3].Value.ToString().Trim();
                int _num = int.Parse(row.Cells[2].Value.ToString());
                if (cut == textBox1.Text.Trim())
                {
                    row.Cells[2].Value = _num - bignum;
                    break;
                }
            }
            textBox2.Text = "0";
            MessageBox.Show("单步模拟成功！", "提示！");
        }

        private void Button3_Click(object sender, System.EventArgs e)
        {
            button3.Enabled = false;
            button2.Enabled = false;
            button3.Text = "模拟中...";
            Task.Run(() =>
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                foreach (DataGridViewRow row in dataGridView3.Rows)
                {
                    Invoke(new Action(() =>
                    {
                        row.DefaultCellStyle.BackColor = System.Drawing.Color.YellowGreen;
                    }));
                    string[] cuttable = row.Cells[3].Value.ToString().Trim().Split('+');
                    int.TryParse(row.Cells[2].Value.ToString().Trim(), out int bignum);
                    row.Cells[2].Value = 0;
                    foreach (var item in cuttable)
                    {
                        string[] o = item.Split('*');
                        decimal length = 0;
                        int num = 1;
                        if (o.Length == 1)
                        {
                            decimal.TryParse(o[0], out length);
                        }
                        else if (o.Length == 2)
                        {
                            decimal.TryParse(o[0], out length);
                            int.TryParse(o[1], out num);
                        }
                        foreach (DataGridViewRow row1 in dataGridView1.Rows)
                        {
                            string _length = row1.Cells["长度"].Value.ToString().Trim();
                            if (_length == length.ToString())
                            {
                                int _num = int.Parse(row1.Cells["已生产支数"].Value.ToString().Trim());
                                row1.Cells["已生产支数"].Value = _num + num * bignum;
                                row1.Cells["已生产支数"].Style.BackColor = System.Drawing.Color.YellowGreen;
                            }
                            int jhNum = int.Parse(row1.Cells["需求支数"].Value.ToString());
                            int scNum = int.Parse(row1.Cells["已生产支数"].Value.ToString());
                            row1.Cells["实际欠支数"].Value = jhNum - scNum;
                        }
                    }
                    Thread.Sleep(SleepTime);
                    foreach (DataGridViewRow row3 in dataGridView1.Rows)
                    {
                        row3.Cells["已生产支数"].Style.BackColor = System.Drawing.Color.White;
                    }
                    Thread.Sleep(SleepTime);
                }
                Invoke(new Action(() =>
                {
                    button3.Enabled = true;
                    button3.Text = "批量模拟";
                    button2.Enabled = true;
                }));
                sw.Stop();
                TimeSpan ts = sw.Elapsed;
                MessageBox.Show("批量模拟成功，耗时：" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds + "秒" + ts.Milliseconds + "毫秒", "提示！");
            });
        }

        private void 导出锯切表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                DataTable dataTable = ((DataTable)dataGridView3.DataSource).Select().CopyToDataTable();
                dataTable.Columns[0].ColumnName = "是否有非计划";
                dataTable.Columns[1].ColumnName = "大料长度";
                dataTable.Columns[2].ColumnName = "大料支数";
                dataTable.Columns[3].ColumnName = "锯切组合";
                string path = saveFileDialog1.FileName;
                NopiHelp.ExportExcel(dataTable, path, sheetName + "锯切表");
                MessageBox.Show("保存成功！", "提示！");
            }
        }

        private void 导出匹配结果表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                DataTable dataTable = ((DataTable)dataGridView1.DataSource).Select().CopyToDataTable();
                dataTable.Columns[0].ColumnName = "长度";
                dataTable.Columns[1].ColumnName = "需求支数";
                dataTable.Columns[2].ColumnName = "计算产出支数";
                dataTable.Columns[3].ColumnName = "计算欠支数";
                dataTable.Columns[4].ColumnName = "实际欠支数";
                dataTable.Columns[5].ColumnName = "已生产支数";
                string path = saveFileDialog1.FileName;
                NopiHelp.ExportExcel(dataTable, path, sheetName + "匹配结果明细表");
                MessageBox.Show("保存成功！", "提示！");
            }
        }

        private void 大料剩余表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                DataTable dataTable = ((DataTable)dataGridView4.DataSource).Select().CopyToDataTable();
                dataTable.Columns[0].ColumnName = "长度";
                dataTable.Columns[1].ColumnName = "剩余支数";
                dataTable.Columns[2].ColumnName = "已用支数";
                dataTable.Columns[3].ColumnName = "未用支数";
                string path = saveFileDialog1.FileName;
                NopiHelp.ExportExcel(dataTable, path, sheetName + "大料剩余表");
                MessageBox.Show("保存成功！", "提示！");
            }
        }
    }
}